﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class WorkOrderTaskControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["action"] == "edit" || Request.QueryString["action"] == "add")
                {
                    txtAssignTo.Visible = false;
                    btnEditTask.Visible = false;
                    btnSaveTask.Visible = true;
                }
            }
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            RSSBMCommonFunctions.SetControlsEnabledState(this, bstate);
        }
        public bool LoadWorkOrderTaskDataByID(int companyid, int WorkOrderid, int taskid)
        {
            bool bHaveData = false;
            int locationid = 0;

            if (companyid > 0)
            {
                RSSBMDataLookupLoader.LoadAssignToCHK(companyid, chkAssignTo);
                RSSBMDataLookupLoader.LoadStatusDDL(companyid, "TASK_CAT", ddlTaskStatus);

                if (WorkOrderid > 0)
                {
                    txtWorkOrderId.Text = WorkOrderid.ToString();
                    if(taskid > 0)
                    {
                        if (Request.QueryString["action"] == "edit")
                           btnDeleteTask.Visible = true;
                        string strSQL = "SELECT t.TaskId, t.TaskName, t.Description, t.Response, t.StartDT, t.EndDT, t.LaborCost, t.DiscountPercent, t.DiscountAmount,";
                        strSQL = strSQL + " t.WorkOrderId, t.AssignTo, t.LocationId, t.StatusId, t.CompanyId";
                        strSQL = strSQL + " FROM rs_tblWorkOrderTask t WHERE t.workorderid=@WorkOrderId AND t.TaskId=@taskid";
                        strSQL = strSQL + " AND t.CompanyId=@CompanyId ORDER BY t.StartDT DESC";

                        SqlCommand myCommand;
                        SqlParameter param;
                        SqlConnection myConnection;
                        myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                        myCommand = new SqlCommand(strSQL, myConnection);
                        SqlDataReader myDataReader;

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@Companyid";
                        param.Value = companyid;
                        myCommand.Parameters.Add(param);

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@WorkOrderid";
                        param.Value = WorkOrderid;
                        myCommand.Parameters.Add(param);

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@Taskid";
                        param.Value = taskid;
                        myCommand.Parameters.Add(param);

                        myConnection.Open();
                        myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                        if (myDataReader.HasRows)
                        {
                            myDataReader.Read();
                            if (myDataReader["LocationId"] != DBNull.Value)
                                locationid = int.Parse(myDataReader["LocationId"].ToString());

                            txtTaskId.Text = taskid.ToString();
                            txtWorkOrderId.Text = myDataReader["workorderid"].ToString();
                            //txtLocationId.Text = myDataReader["LocationId"].ToString();
                            txtTaskName.Text = myDataReader["TaskName"].ToString();

                            if (myDataReader["StartDT"] != DBNull.Value)
                            {
                                DateTime startdt = Convert.ToDateTime(myDataReader["StartDT"].ToString());
                                txtStartTime.Text = startdt.ToShortTimeString();
                                txtStartDate.Text = startdt.ToShortDateString();
                            }

                            if (myDataReader["EndDT"] != DBNull.Value)
                            {
                                DateTime enddt = Convert.ToDateTime(myDataReader["EndDT"].ToString());
                                txtEndTime.Text = enddt.ToShortTimeString();
                                txtEndDate.Text = enddt.ToShortDateString();
                            }

                            txtDescription.Text = myDataReader["Description"].ToString();
                            txtResponse.Text = myDataReader["Response"].ToString();
                            ddlTaskStatus.SelectedValue = myDataReader["StatusId"].ToString();

                            txtLaborCost.Text = myDataReader["LaborCost"].ToString();
                            txtDiscountPercent.Text = myDataReader["DiscountPercent"].ToString();
                            txtDiscountAmount.Text = myDataReader["DiscountAmount"].ToString();
                            txtAssignTo.Text = myDataReader["AssignTo"].ToString();
                            RSSBMCommonFunctions.SetMultiSelectList(myDataReader["AssignTo"].ToString(), chkAssignTo);
                            bHaveData = true;

                            if (Request.QueryString["action"] == "edit")
                            {
                                btnDeleteTask.Visible = true;
                            }
                            else
                            {
                                SetControlEnabledState(false);
                            }
                        }
                        myConnection.Close();
                    }
                }
                if (Request.QueryString["workorderid"] != null)
                {
                    
                    WorkOrderid = Convert.ToInt32(Request.QueryString["workorderid"].ToString());
                    locationid = RSSBMCommonFunctions.GetLocationIDByWorkOrderID(companyid, WorkOrderid);
                }
                if (companyid > 0 && locationid > 0)
                {
                    ucLocationHeaderControl.LoadLocationHeader(companyid, locationid);
                }
            }
            return bHaveData;
        }

        

        protected void btnEditTask_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                Response.Redirect(Request.Url.ToString() + "&action=edit");
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
        protected void btnSaveTask_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;

            int LocationId = ucLocationHeaderControl.LocationId;
            int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);
            int TaskId = txtTaskId.Text == "" ? 0 : Convert.ToInt32(txtTaskId.Text);

            string TaskName = txtTaskName.Text.Trim();
            string StartDT = txtStartDate.Text + " " + txtStartTime.Text.Trim();
            string EndDT = txtEndDate.Text + " " + txtEndTime.Text.Trim();
            StartDT = StartDT.Trim();
            EndDT = EndDT.Trim();
            string Description = txtDescription.Text.Trim();
            string Response = txtResponse.Text.Trim();

            float LaborCost = txtLaborCost.Text == "" ? 0 : Convert.ToSingle(txtLaborCost.Text);
            int DiscountPercent = txtDiscountPercent.Text == "" ? 0 : Convert.ToInt32(txtDiscountPercent.Text);
            float DiscountAmount = txtDiscountAmount.Text == "" ? 0 : Convert.ToSingle(txtDiscountAmount.Text);

            string AssignTo = RSSBMCommonFunctions.GetMultiSelectValue(chkAssignTo);
            int StatusID = Convert.ToInt32(ddlTaskStatus.SelectedValue);

            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaskName", SqlDbType.NVarChar, 100, ParameterDirection.Input, TaskName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.NVarChar, -1, ParameterDirection.Input, Description);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Response", SqlDbType.NVarChar, -1, ParameterDirection.Input, Response);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@StartDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(StartDT));
            
            if(EndDT.Length > 0)
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@EndDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(EndDT));

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LaborCost", SqlDbType.Money, 0, ParameterDirection.Input, LaborCost);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@DiscountPercent", SqlDbType.SmallInt, 0, ParameterDirection.Input, DiscountPercent);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@DiscountAmount", SqlDbType.Money, 0, ParameterDirection.Input, DiscountAmount);

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaskID", SqlDbType.Int, 0, ParameterDirection.Input, TaskId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@AssignTo", SqlDbType.NVarChar, 100, ParameterDirection.Input, AssignTo);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@StatusId", SqlDbType.Int, 0, ParameterDirection.Input, StatusID);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveWorkOrderTask");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();
            ucModalActionMessageControl.ShowModal("Task successfully saved!", prevurl, true);
        }
        protected void btnDeleteTask_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int CompanyId = userIdentity.RSCompanyId;
                int TaskId = txtTaskId.Text == "" ? 0 : Convert.ToInt32(txtTaskId.Text);
                int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);

                SqlCommand sqlCmd = new SqlCommand();
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaskId", SqlDbType.Int, 0, ParameterDirection.Input, TaskId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);

                SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblWorkOrderTask WHERE workorderid=@WorkOrderId AND TaskId=@TaskId AND CompanyId=@CompanyId");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                string prevurl = string.Empty;
                if (Session["PreviousURL"] != null)
                    prevurl = Session["PreviousURL"].ToString();
                else
                    prevurl = Request.UrlReferrer.ToString();
                ucModalActionMessageControl.ShowModal("Task successfully deleted from WorkOrder!", prevurl, true);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
       
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();
            if (Request.Url.ToString().Contains("RSManageWorkOrderTask.aspx"))
                Response.Redirect("~/RS/SBM/RSWorkOrderDetail.aspx?workorderid=" + txtWorkOrderId.Text);
            else
                Response.Redirect(prevurl);
        }
    }

    
}